package com.dongge.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 增删改查的模板
 * Created by 东哥 on 2015/10/18.
 */
public abstract class CURDDaoBase<T> {

    private SessionFactory sessionFactory;
    private Class<T> clazz = null;

    public CURDDaoBase() {

        try{
            ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass();
            clazz = (Class<T>)parameterizedType.getActualTypeArguments()[0];
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }


    protected Session getSession(){
        return  sessionFactory.getCurrentSession();
    }

    /**
     * 增
     * @param model
     */
    public void save(T model){
        if(model!=null)
        {
            getSession().save(model);
        }
    }

    /**
     * 改
     * @param model
     */
    public void update(T model){
        if(model!=null){
            getSession().update(model);
        }
    }

    /**
     * 查一个
     * @param id
     */
    public T get(Long id){
        if(id != null){
            return (T)getSession().get(clazz, id);
        }
        return  null;
    }

    /**
     * 查询所有
     * @return
     */
    public List<T> getAll(){
        String hsql = "from "+clazz.getSimpleName();
        return getSession().createQuery(hsql).list();
    }

    /**
     * 删
     * @param id
     */
    public void delete(Long id){
        T model = get(id);
        if(model != null)
        {
            getSession().delete(model);
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
